package com.forekonw.demo12;

import java.awt.image.VolatileImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能类
 * 向文件中写数据
 * 从文件中读取数据
 */
public class ReadWrite {


    public void write(List<Student> students,String filename){
        //对集合遍历
        //遍历一次拿到一个对象,通过get方法获取信息
        //将信息写入到目标文件当中   换行
        //释放资源
        try {
            FileWriter f = new FileWriter(filename);
            BufferedWriter bf = new BufferedWriter(f);
            for (Student s:students) {
                String num = s.getNum();
                bf.write(num);
                bf.write(" ");
                String name = s.getName();
                bf.write(name);
                bf.write(" ");
                String age = s.getAge();
                bf.write(age);
                bf.write(" ");
                String tel = s.getTel();
                bf.write(tel);
                bf.write(" ");
            }
            bf.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 1选流
     * 2读取源文件中的一行   一个字符串(String)
     * 拆分字符串String  split(根据空格拆分):String[]
     * 把数组 中的对象取出,放到Student对象中
     * 再将对象放到list集合中
     * 3返回list集合
     * @param filename
     * @return
     */
    public List<Student> read(String filename){
        List<Student> ss = new ArrayList<>();
        try {
            FileReader file = new FileReader(filename);
            BufferedReader br = new BufferedReader(file);
            String line = br.readLine();
            while (line!=null){
                String[] str = line.split(" ");
                    for (int i = 0 ; i <str.length;i++){
                        Student stud = new Student();
                        stud.setNum(str[0]);
                        stud.setName(str[1]);
                        stud.setAge(str[2]);
                        stud.setTel(str[3]);
                        ss.add(stud);
                        line = br.readLine();

                    }
                }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ss;
    }


}
